package com.xyy.saas.payment.adpater.yop;

import com.xyy.saas.payment.common.Constants;
import com.xyy.saas.payment.common.exception.PaymentException;
import com.xyy.saas.payment.cores.enums.ResultCodeEnum;
import com.xyy.saas.payment.util.JSONUtils;
import com.xyy.saas.payment.util.PicUtil;
import com.yeepay.yop.sdk.exception.YopClientException;
import com.yeepay.yop.sdk.service.sys.SysClient;
import com.yeepay.yop.sdk.service.sys.SysClientBuilder;
import com.yeepay.yop.sdk.service.sys.model.MerchantQualUploadMerFileUploadRespDtoResult;
import com.yeepay.yop.sdk.service.sys.request.*;
import com.yeepay.yop.sdk.service.sys.response.*;

import java.io.File;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class YopFileUpload {
// 该Client线程安全，请使用单例模式，多次请求共用
private final SysClient api = SysClientBuilder.builder().build();

  /**
  * 子商户入网资质文件上传
  */
  public String fileUpload(File file) throws PaymentException {
    MerchantQualUploadRequest request = new MerchantQualUploadRequest();
    request.setMerQual(file);

    try {
       MerchantQualUploadResponse response = api.merchantQualUpload(request);
       log.info("YopFileUpload#fileUpload request:{} response:{}", file.getName(), JSONUtils.toJSON(response));
       MerchantQualUploadMerFileUploadRespDtoResult result = response.getResult();

       if(!Constants.YOP_UPLOAD_SUCCESS_CODE.equals(result.getReturnCode())) {
           throw new PaymentException(result.getReturnCode(), result.getReturnMsg());
       }

       return result.getMerQualUrl();
    }
    catch(Exception ex) {
       log.error("YopFileUpload#fileUpload error, file=" + file.getName() + ", errorMsg=" + ex.getMessage() ,ex);

       if(ex instanceof PaymentException) {
          throw ex;
       }
       else if(ex instanceof YopClientException) {
          throw new PaymentException(ResultCodeEnum.YOP_SYSTEM_ERROR.getCode(), ex.getMessage());
       }

       throw new PaymentException(ResultCodeEnum.YOP_SYSTEM_ERROR);
    }
  }
}